<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/12
 * Time: 16:51
 */

namespace app\admin\model;


use think\Model;

class Ad extends Model
{
    /*
     * 查询当前session下用户名
     */
    public function getSessionName($sessionId)
    {
        //查询登录名
        $sessionName = db('admin_user')->where('id',$sessionId)->value('user_account');
        return $sessionName;
    }

    public function getList($keyword,$pageNum, $num_per_page)
    {
        $list = db("ad")
            ->where(function ($query) use ($keyword) {
                if (!empty($keyword)) {
                    $query->where('ad_name', 'like', "%{$keyword}%");
                }
            })
            ->where('is_delete',0)
            ->page($pageNum, $num_per_page)
            ->order('update_time desc')
            ->select();
        return $list;
    }

    public function getCount($keyword)
    {
        $count = db('ad')
            ->where(function ($query) use ($keyword) {
                if (!empty($keyword)) {
                    $query->where('ad_name', 'like', "%{$keyword}%");
                }
            })
            ->where("is_delete",0)
            ->count();
        return $count;
    }

    public function doAdd($info)
    {
        $info['create_time'] = $info['update_time'] = time();
        $result = db('ad')
            ->insert($info);
        if (!$result) {
            exception('添加失败');
        }
    }

    public function modify($id)
    {
        $info = db('ad')
            ->where('ad_id', $id)
            ->find();
        return $info;
    }

    public function doModify($info)
    {
        $ad_id = $info['ad_id'];
        unset($info['ad_id']);
        $result = db('ad')
            ->where('ad_id',$ad_id)
            ->update($info);
        if(!$result){
            exception('修改失败');
        }
    }
    /**
     * @param $id
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function doDelete($id){
        $result = db('ad')
            ->where('ad_id',$id)
            ->delete();
        if(!$result){
            exception("删除失败");
        }
    }
}